package internal

import (
	"fmt"
	"net"
	"serverlog/src/internal/icode"
)

type SessionAdmin struct {
	//会话增加id
	id uint32
	//退出chan,单独开个协程来接收删除
	quit chan uint32
	//加个映射
	smap map[uint32]iinternal.ISession
}

func NewSessionAdmin() iinternal.ISessionAdmin {
	s := &SessionAdmin{
		id:   0,
		quit: make(chan uint32),
		smap: make(map[uint32]iinternal.ISession),
	}

	go s.quitProc()

	return s
}

func (s *SessionAdmin) NewSession(conn net.Conn, notify chan iinternal.INotifyMsg) iinternal.ISession {
	ns := NewSession(s.id, s.quit, conn, notify)

	s.smap[s.id] = ns
	s.id += 1

	return ns
}

func (s *SessionAdmin) quitProc() {
	//开个协程读取删除信息
	for {
		select {
		case id, ok := <-s.quit:
			if !ok {
				return
			}
			delete(s.smap, id)
			fmt.Println("sessionadmin remove id=", id)
		}
	}
}

func (s *SessionAdmin) Exit() {
	//....
	// close(s.quit)
}

func (s *SessionAdmin) GetSessionNums() uint32 {
	return uint32(len(s.smap))
}
